// const md5 = require("md5");
import { JWTHelper } from "../../utils/JWTHelper";
import { ForbiddenError } from "../../utils/errors";
import { pathToRegexp } from "path-to-regexp";

export interface IVerificationWhiteList {
  path: string;
  methods: string[];
}

function verificationToken(whiteList: IVerificationWhiteList[]) {
  return (req: any, _res: any, next: any) => {
    const result = whiteList.filter((item) => {
      const reg = pathToRegexp(item.path);

      return reg.test(req.path) && item.methods.includes(req.method.toLocaleLowerCase());
    });

    // 进入此if证明不需要验证
    if (result.length) {
      next();
      return;
    }
    // 往下走证明需要验证
    // 但是没有 authorization 字段，证明未登录，直接抛出错误
    if (!req.headers["authorization"]) {
      throw new ForbiddenError("权限不足，请先登录");
    }

    let token = req.headers["authorization"].split(" ")[1]; // 获取请求头中的token

    const verResult = JWTHelper.verify(token);
    req.token = verResult;
    next();
  }
}

export default verificationToken;
